package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.Dispatcher;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;
import game2dai.maths.MathUtils;
import game2dai.steering.SBF;

public class PlayerPrepareForKickOff extends State implements Constants {

	private static PlayerPrepareForKickOff instance = null;

	public static PlayerPrepareForKickOff state(){
		if(instance == null){
			instance = new PlayerPrepareForKickOff();
			instance.name = "Prep for Kickoff";
		}
		return instance;
	}

	@Override
	public void enter(BaseEntity owner) {
		PlayerBase player = (PlayerBase) owner;
		player.regionToUse = player.defendRegion;
		player.targetPos.set(player.team.pitch.getRegion(player.regionToUse).centre);
		player.targetPos.add(MathUtils.randomClamped(), MathUtils.randomClamped());
		player.headingAtRest(player.team.teamHeading);
		player.AP().arriveOn(player.targetPos, SBF.FAST);
	}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		PlayerBase player = (PlayerBase) owner;
		if(player.isGoalKeeper()){ // Goal keeper
			if(player.isNearTarget()){
				Dispatcher.dispatch(0, player.ID(), player.team.ID(), AT_TARGET);
				player.FSM().changeState(KeeperTendGoal.state());			
			}
		}
		else { // Field player
			if(player.isAtTarget()){
				Dispatcher.dispatch(0, player.ID(), player.team.ID(), AT_TARGET);
				player.moveTo(player.targetPos);
				player.FSM().changeState(PlayerWait.state());
			}
		}
	}

	@Override
	public void exit(BaseEntity owner) {
		PlayerBase player = (PlayerBase) owner;
		player.AP().arriveOff();
	}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		return false;
	}

}
